import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_ORIGIN_API, // 代理路径
  // baseURL: "http://localhost:8000/api/",
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  },
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom status
   * Here is just an user
   * You can also judge the status by HTTP Status status
   */
  (response) => {
    // 判断响应是否为二进制
    if (!response.headers['content-type'].includes('application/json')) {
      return response
    }
    // 获取请求信息
    const { data } = response
    // 非法授权
    if (data.status === 401) {
      // 删除token
      removeToken()
    }
    // 非法授权
    else if (data.status === 403) {
      Message({
        message: '对不起您无权访问此资源!',
        type: 'error',
        duration: 5 * 1000,
        showClose: true,
      })
      // 重新获取
      store.dispatch('user/getInfo')
    }
    // 发出错误信息
    else if (data.status !== 200) {
      Message({
        message: data.message || '请求失败!',
        type: 'error',
        duration: 5 * 1000,
        showClose: true,
      })
      return Promise.reject(new Error(data.message || '请求错误!'))
    } else {
      return data
    }
  },
  (error) => {
    if (!error || !error.response) {
      Message({
        message: error.message || '网络错误!',
        type: 'error',
        duration: 5 * 1000,
        showClose: true,
      })
      return Promise.reject(error)
    }
    const { data } = error.response
    console.log(error.response) // for debug
    Message({
      message: data.message || '服务器异常!',
      type: 'error',
      duration: 5 * 1000,
      showClose: true,
    })
    return Promise.reject(error)
  },
)

export default service
